<script setup>
import {defineProps, reactive, ref} from "vue";
import AddScoringManage from "@/components/scoring/addScoringManage.vue";
import {AddScoring} from "@/api/scoring.js";
import {ElMessage} from "element-plus";
import {userInfoStore} from "@/store/userInfoStore.js";
import {userTokenStore} from "@/store/userTokenStore.js";
import avatar from "@/assets/avatar.jpg";
import {Loading, Plus} from "@element-plus/icons-vue";

const isUpdate = ref(false);
const doUpdate = (_scoringResult)=>{
  console.log("_scoringResult: ",_scoringResult)
  scoringResult.value.resultDesc = _scoringResult.resultDesc;
  scoringResult.value.id = _scoringResult.id;
  scoringResult.value.resultName = _scoringResult.resultName;
  scoringResult.value.resultPicture = _scoringResult.resultPicture;
  scoringResult.value.resultProp = _scoringResult.resultProp;
  scoringResult.value.resultScoreRange = _scoringResult.resultScoreRange||null;
  isUpdate.value = true;
  console.log("scoringResult: ",scoringResult.value)
}
const addScoringResult = ()=>{
  scoringResult.value = {
    id:null,
    resultName:"",
    resultDesc:"",
    resultPicture:"",
    resultProp:[],
    resultScoreRange:null
  };
  isUpdate.value = false;
}
const props = defineProps({
  appId: {
    type: String,
    default: ""
  },
  appName:{
    type:String,
    default:""
  },
  appType:{
    type:String,
  },
  scoringStrategy:{
    type:String,
  }
});

const scoringResult = ref({
  id:null,
  resultName:"",
  resultDesc:"",
  resultPicture:"",
  resultProp:[],
  resultScoreRange:null
})
// 绑定输入框的值
const inputValue = ref('');
// 添加标签到结果集数组
const addTag = () => {
  if (inputValue.value) {
    scoringResult.value.resultProp.push(inputValue.value);
    inputValue.value = '';
  }
};

// 从结果集数组中移除标签
const removeTag = (index) => {
  scoringResult.value.resultProp.splice(index, 1);
};
//刷新列表
const Refresh = ref(null);

const handleSubmit = async () => {
  const params = {
    ...scoringResult.value,
    appId: props.appId,
    resultPicture:imgUrl.value
  }
  if(params.resultProp.length===0){
    params.resultProp = null;
  }
  console.log("params: ",params)
  const data = await AddScoring(params);
  if(Refresh.value){
    await Refresh.value.fetchScoreList()
  }
  if(data.code===0){
    addScoringResult();
    ElMessage.success("操作成功");
  }else{
    ElMessage.error("操作失败");
  }
}

const rules = reactive({
  resultName:[
    {
      required: true, message: '请输入你的结果名称', trigger: 'blur',
    }
  ],
  resultDesc:[
    {
      required: true, message: '请输入你的结果描述', trigger: 'blur',
    }
  ],
  resultProp:[
    {
      required: true, message: '请输入你的结果集合', trigger: 'blur',
    },
  ],
  resultScoreRange:[
    {
      required: true, message: '请输入你的得分', trigger: 'blur',
    }
  ]
})

const uploadRef = ref()
const InfoStore = userInfoStore();
const TokenStore = userTokenStore();
const imgUrl= ref(InfoStore.info.user_pic);
//笔记上传成功与否


// 在data部分添加loading状态
const isUploading = ref(false);
const uploadLoading = ref(null); // 用于控制单个上传的loading

// 修改上传方法
const FileUpload = (result) => {
  if (uploadLoading.value) {
    uploadLoading.value.close();
    uploadLoading.value = null;
  }
  isUploading.value = false;
  imgUrl.value = result.data;
  ElMessage.success("上传成功！");
};
const handleUploadError = (error) => {
  isUploading.value=false;
  if (uploadLoading.value) {
    uploadLoading.value.close();
    uploadLoading.value = null;
  }
  console.log(error);
  ElMessage.error("上传失败");
};
// 修改上传前的处理
const beforeUpload =  (file) => {
  isUploading.value = true;
  // uploadLoading.value = Loading.service({
  //   lock: true,
  //   text: '图片上传中...',
  //   background: 'rgba(0, 0, 0, 0.7)'
  // });
  // console.log("uploadLoading",uploadLoading.value)
  let isJPG = false,
      fileType = file.type.split('/')[0];
  isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024;

  if (fileType !== 'image' || isLt2M > 2) {
    ElMessage.error("请上传2M以内的图片文件!");
    return false
  }
  return true;
};
</script>

<template>
  <div id="addQuestionPage">
    <el-card>
      <h1>{{scoringResult}}</h1>
      <h2 style="margin-bottom: 32px" v-if="!isUpdate">创建评分结果集合</h2>
      <h2 style="margin-bottom: 32px" v-else>修改评分结果集合</h2>
      <el-form
          :model="scoringResult"
          :style="{ width: '480px' }"
          label-position="left"
          :rules="rules"
          @submit.prevent
      >
        <el-form-item label="应用 ID">
          <span>{{ appId }}</span>
        </el-form-item>
        <el-form-item v-if="isUpdate" label="评分策略 ID">
          <span>{{ scoringResult.id }}</span>
        </el-form-item>
        <el-form-item label="应用名称 ">
          <span>{{ appName }}</span>
        </el-form-item>
        <el-form-item label="结果名称" prop="resultName">
          <el-input v-model="scoringResult.resultName" placeholder="请输入结果名称"></el-input>
        </el-form-item>
        <el-form-item label="结果描述" prop="resultDesc">
          <el-input v-model="scoringResult.resultDesc" placeholder="请输入结果描述"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-col :span="12" style="display: flex; flex-direction: column; align-items: center; gap: 12px;">
            <el-upload
                ref="uploadRef"
                class="avatar-uploader"
                :show-file-list="false"
                :headers = "{'Authorization':TokenStore.token}"
                action="/api/file/upload"
                name="file"
                :on-success="FileUpload"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                auto-upload
                :disabled="Number(props.scoringStrategy)===1"
            >

              <div v-if="isUploading" class="avatar-wrapper loading-wrapper">
                <el-icon class="is-loading" :size="40">
                  <Loading />
                </el-icon>
                <div class="loading-text">上传中...</div>
              </div>
              <div v-else-if="imgUrl" class="avatar-wrapper">
                <img :src="imgUrl" class="avatar" style="width: 200px;height: 200px"/>
              </div>
              <div v-else class="avatar-wrapper">
                <img :src="avatar" class="default-avatar" />
              </div>
            </el-upload>
            <el-button
                type="primary"
                :icon="Plus"
                size="large"
                @click="uploadRef.$el.querySelector('input').click()"
                class="upload-button"
                :disabled="Number(props.scoringStrategy)===1"
            >
              选择图片
            </el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="结果集" v-if="appType==='1'" prop="resultProp">
          <el-input
              v-model="inputValue"
              @keyup.enter="addTag"
              @blur="addTag"
              placeholder="输入结果集"
          >
            <template #append>
              <el-button @click="addTag">添加</el-button>
            </template>
          </el-input>
          <el-tag
              v-for="(tag, index) in scoringResult.resultProp"
              :key="index"
              closable
              @close="removeTag(index)"
          >
            {{ tag }}
          </el-tag>
        </el-form-item>
        <el-form-item label="得分范围" v-else prop="resultScoreRange">
          <el-input-number v-model="scoringResult.resultScoreRange" placeholder="请输入得分范围"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-space size="large">
            <el-button type="primary" native-type="button" style="width: 120px" @click="handleSubmit" :disabled="Number(props.scoringStrategy)===1">
              提交
            </el-button>
            <el-text v-if="Number(props.scoringStrategy)===1" type="warning">注意此应用为AI评分，无需设置评分策略</el-text>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <AddScoringManage :appId = "appId" :doUpdate = "doUpdate" :addScoringResult="addScoringResult" :appType="props.appType" ref="Refresh"/>
    </el-card>
  </div>
</template>

<style scoped>
.loading-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #888;
}

.loading-text {
  margin-top: 10px;
  font-size: 14px;
}
.avatar-wrapper {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-button {
  margin-top: 12px;
  width: 200px;
}
</style>